/**
 * @file      config_storage.c
 * @brief
 * @version   1.0
 * @date      2023.12.14
 *
 * @copyright Copyright (c) 2018 UCchip Technology Co.,Ltd. All rights reserved.
 *
 * Change Logs:
 * Date          Author       Notes
 * 2023.12.14    zhdiao       the first version
 *
 */

#include <rtthread.h>
#include <rtdevice.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "config_storage.h"

#define DBG_ENALE
#define DBG_SECTION_NAME "config_storage"
#define DBG_LEVEL DBG_INFO
#include <rtdbg.h>

int config_file_get_len(char *file)
{
    rt_err_t ret;
    struct stat config_file_stat = {0};

    if (stat(CONFIG_FILE_PATH, &config_file_stat))
    {
        LOG_E("get config file stat failed");
        return -RT_ERROR;
    }

    return config_file_stat.st_size;
}

int config_file_read(char *file, void *data, unsigned int size)
{
    int fd;
    int read_size, ret = 0;

    fd = open(file, O_RDONLY);
    if (fd < 0)
    {
        LOG_E("config_file_read open file :%s failed, exit", CONFIG_FILE_NAME);
        ret = -RT_EINVAL;
        goto open_err_out;
    }

    read_size = read(fd, data, size);
    if (read_size < 0)
    {
        LOG_E("read file :%s failed, exit", CONFIG_FILE_NAME);
        ret = -RT_ERROR;
        goto read_err_out;
    }

    ret = read_size;

read_err_out:
    close(fd);

open_err_out:
    return ret;
}

int config_file_write(char *file, const void *data, unsigned int size)
{
    int fd;
    int write_size, ret = 0;

    fd = open(file, O_WRONLY | O_TRUNC);
    if (fd < 0)
    {
        LOG_E("config_file_write open %s :%s failed, exit", file, CONFIG_FILE_NAME);
        ret = -RT_EINVAL;
        goto open_err_out;
    }

    write_size = write(fd, data, size);
    if (write_size < 0)
    {
        LOG_E("write file :%s failed, exit", CONFIG_FILE_NAME);
        ret = -RT_ERROR;
        goto write_err_out;
    }

    ret = write_size;

write_err_out:
    close(fd);

open_err_out:
    return ret;
}

int config_file_init(void)
{
    int fd;

    fd = open(CONFIG_FILE_PATH, O_CREAT);
    if (fd < 0)
    {
        LOG_E("file %s, open failed", CONFIG_FILE_NAME);
        return -RT_ERROR;
    }

    LOG_I("%s check success", FACTORY_FILE_PATH);
	close(fd);
	
	fd = open(FACTORY_FILE_PATH, O_CREAT);
    if (fd < 0)
    {
        LOG_E("file %s, open failed", FACTORY_FILE_PATH);
        return -RT_ERROR;
    }
    LOG_I("%s check success", FACTORY_FILE_PATH);
    close(fd);
}
INIT_APP_EXPORT(config_file_init);
